package com.wang.springbootinit.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.springbootinit.exception.BusinessException;
import com.wang.springbootinit.mapper.TrainingMapper;
import com.wang.springbootinit.model.dto.TrainingQueryDTO;
import com.wang.springbootinit.model.dto.TrainingUploadDTO;
import com.wang.springbootinit.model.entity.Training;
import com.wang.springbootinit.model.entity.User;
import com.wang.springbootinit.service.FileService;
import com.wang.springbootinit.service.TrainingService;
import com.wang.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 培训服务实现类
 * 处理培训相关的业务逻辑，包括培训内容的增删改查
 */
@Service
@Slf4j
public class TrainingServiceImpl extends ServiceImpl<TrainingMapper, Training> implements TrainingService {
    @Autowired
    private TrainingMapper trainingMapper;
    @Autowired
    private FileService fileService; // 假设已有文件上传服务
    @Autowired
    private UserService userService;

    /**
     * 添加新的培训记录
     * @param uploadDTO 培训上传数据传输对象，包含培训信息、视频和图片
     * @return 添加是否成功
     */
    @Override
    public boolean addTraining(TrainingUploadDTO uploadDTO, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        // 处理文件上传
        String videoUrl = null;
        if (uploadDTO.getVideo() != null) {
            videoUrl = fileService.uploadFile(uploadDTO.getVideo());
        }

        List<String> imageUrlList = new ArrayList<>();
        if (uploadDTO.getImages() != null) {
            for (MultipartFile image : uploadDTO.getImages()) {
                String imageUrl = fileService.uploadFile(image);
                imageUrlList.add(imageUrl);
            }
        }

        Training training = new Training();
        training.setItemName(uploadDTO.getItemName());
        training.setTrainingContent(uploadDTO.getTrainingContent());
        training.setVideoUrl(videoUrl);
        training.setImageUrls(JSONUtil.toJsonStr(imageUrlList));
        training.setCreateTime(LocalDateTime.now());
        training.setUpdateTime(LocalDateTime.now());
        training.setCreateBy(loginUser.getUserName());

        int insert = trainingMapper.insert(training);
        if (insert > 0) {
            return true;
        }
        throw new BusinessException("添加失败");
    }

    @Override
    public boolean updateTraining(TrainingUploadDTO uploadDTO,HttpServletRequest request) {
        // 参数校验
        if (uploadDTO == null || uploadDTO.getTrainingId() == null) {
            throw new BusinessException("参数不完整");
        }
        
        // 获取原有培训记录
        Training existTraining = trainingMapper.selectById(uploadDTO.getTrainingId());
        if (existTraining == null) {
            throw new BusinessException("培训记录不存在");
        }

        // 处理新的文件上传
        String videoUrl = existTraining.getVideoUrl();
        if (uploadDTO.getVideo() != null) {
            // 删除原有视频
            if (StringUtils.isNotBlank(videoUrl)) {
                fileService.deleteFile(videoUrl);
            }
            // 上传新视频
            videoUrl = fileService.uploadFile(uploadDTO.getVideo());
        }

        // 处理图片更新
        List<String> imageUrlList = new ArrayList<>();
        if (uploadDTO.getImages() != null) {
            // 删除原有图片
            if (StringUtils.isNotBlank(existTraining.getImageUrls())) {
                List<String> oldImages = JSONUtil.toList(existTraining.getImageUrls(), String.class);
                oldImages.forEach(fileService::deleteFile);
            }
            // 上传新图片
            for (MultipartFile image : uploadDTO.getImages()) {
                String imageUrl = fileService.uploadFile(image);
                imageUrlList.add(imageUrl);
            }
        }

        // 更新培训记录
        existTraining.setItemName(uploadDTO.getItemName());
        existTraining.setTrainingContent(uploadDTO.getTrainingContent());
        existTraining.setVideoUrl(videoUrl);
        existTraining.setImageUrls(JSONUtil.toJsonStr(imageUrlList));
        existTraining.setUpdateTime(LocalDateTime.now());

        return trainingMapper.updateById(existTraining) > 0;
    }

    @Override
    public boolean deleteTraining(Long trainingId) {
        if (trainingId == null) {
            throw new BusinessException("培训ID不能为空");
        }
        
        // 获取培训记录
        Training training = trainingMapper.selectById(trainingId);
        if (training == null) {
            throw new BusinessException("培训记录不存在");
        }

        // 删除相关文件
        if (StringUtils.isNotBlank(training.getVideoUrl())) {
            fileService.deleteFile(training.getVideoUrl());
        }
        if (StringUtils.isNotBlank(training.getImageUrls())) {
            List<String> images = JSONUtil.toList(training.getImageUrls(), String.class);
            images.forEach(fileService::deleteFile);
        }

        return trainingMapper.deleteById(trainingId) > 0;
    }

    @Override
    public Training getTrainingById(Long trainingId) {
        if (trainingId == null) {
            throw new BusinessException("培训ID不能为空");
        }
        Training training = trainingMapper.selectById(trainingId);
        if (training == null) {
            throw new BusinessException("培训记录不存在");
        }
        return training;
    }

    /**
     * 根据查询条件分页获取培训记录
     * @param queryDTO 查询条件，包含项目名称、时间范围等筛选条件
     * @return 培训记录分页结果
     */
    @Override
    public Page<Training> getTrainingPage(TrainingQueryDTO queryDTO) {
        LambdaQueryWrapper<Training> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(queryDTO.getItemName()), 
                    Training::getItemName, queryDTO.getItemName())
               .ge(queryDTO.getStartTime() != null, 
                   Training::getCreateTime, queryDTO.getStartTime())
               .le(queryDTO.getEndTime() != null, 
                   Training::getCreateTime, queryDTO.getEndTime())
               .orderByDesc(Training::getCreateTime);

        Page<Training> page = new Page<>(queryDTO.getCurrent(), queryDTO.getPageSize());
        return trainingMapper.selectPage(page, wrapper);
    }

    /**
     * 根据项目名称获取相关培训记录
     * @param itemName 项目名称
     * @return 培训记录列表，按创建时间降序排序
     */
    @Override
    public List<Training> getTrainingByItem(String itemName) {
        LambdaQueryWrapper<Training> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Training::getItemName, itemName)
               .orderByDesc(Training::getCreateTime);
        return trainingMapper.selectList(wrapper);
    }
} 